#!/bin/bash

#################################################
# DNSPod-IPv6 shell v0.1
# 使用API动态配置DNSPod的域名IPv6记录
# Gitee https://gitee.com/greenice897/ddns-dnspod-ipv6-shell
# 作者 greenice897
# 原作者 anker<cong.an@qq.com> https://github.com/CongAn/ddnspod-ipv6; 并参考 https://github.com/imki911/ArDNSPod
#################################################

# read configure file
source /usr/local/etc/ddnspod.d/*

# OS Detection
case $(uname) in
    'Linux')
		echo "OS: Linux"
		arIpAddress() {
			# 获得公网ipv6 加上$local_hostNIC变量是可选择网卡（适用多网卡）
			ip addr show $local_hostNIC | grep inet6 | grep "${local_IP_ADDRESS_label}" | sed -n '1p' | sed -e's/^.*inet6 \([^ ]*\)\/.*$/\1/;t;d'
		}
    ;;
    'FreeBSD')
		echo 'OS: FreeBSD'
		exit 100
    ;;
    'WindowsNT')
		echo "OS: Windows"
		exit 100
    ;;
    'Darwin')
		echo "OS: Mac"
		arIpAddress() {
			ifconfig -a | grep 'inet6' | grep 'prefixlen 64 autoconf secured' | sed 's/^.*inet6 //' | sed 's/ .*//'
		}
    ;;
    'SunOS')
		echo 'OS: Solaris'
		exit 100
    ;;
    'AIX')
		echo 'OS: AIX'
		exit 100
    ;;
    *) ;;
esac

# Get data
# arg: type data
# see Api doc: https://www.dnspod.cn/docs/records.html#
dnsapi() {
    #local inter="https://dnsapi.cn/${1:?'Info.Version'}"
    local inter="https://dnsapi.cn/${1}"
    local param="login_token=${LOGIN_ID},${LOGIN_TOKEN}&format=json&${2}"
    echo "${inter}?${param}"
    curl -X POST ${inter} -d "${param}"
    # wget --quiet --no-check-certificate --secure-protocol=TLSv1_2 --output-document=- --post-data $param $inter
}

# Get Domain IP
# arg: domain
getDomainIP() {
    local domainID recordID recordIP recordITEM
    # Get domain ID
    domainID=$(dnsapi "Domain.Info" "domain=${1}")

    domainID=$(echo $domainID | sed 's/.*{"id":"\([0-9]*\)".*/\1/')

    # Get Record ID
    recordID=$(dnsapi "Record.List" "domain_id=${domainID}&sub_domain=${2}&record_type=${record_type}")

    recordITEM=$(echo $recordID | sed 's/.*\("records":\[{"id"\):"[0-9]*".*/\1/')
    if [ "$recordITEM" = '"records":[{"id"' ]; then
        recordID=$(echo $recordID | sed 's/.*\[{"id":"\([0-9]*\)".*/\1/')
    else
        recordID=""
    fi

    # Last IP
    if [ -n "$recordID" ]; then
        recordIP=$(dnsapi "Record.Info" "domain_id=${domainID}&record_id=${recordID}&record_type=${record_type}")

        recordIP=$(echo $recordIP | sed 's/.*,"value":"\([0-9a-z\.:]*\)".*/\1/')
    else
        recordIP=""
    fi

    # Output IP
    case "$recordIP" in
      [1-9a-z]*)
        echo $recordIP
        return 0
        ;;
      *)
        #echo "Get Record Info Failed!"
        return 1
        ;;
    esac
}

# Add domain IP
# arg: main domain  sub domain
addDomainIP() {
    local recordRS recordCD recordIP
    # Get domain ID
    domainID=$(dnsapi "Domain.Info" "domain=${1}")
    domainID=$(echo $domainID | sed 's/.*{"id":"\([0-9]*\)".*/\1/')
    #echo $domainID    
    # Add IP
    recordRS=$(dnsapi "Record.Create" "domain_id=${domainID}&sub_domain=${2}&record_type=${record_type}&record_line=默认&value=${newDomainIP}")
    recordCD=$(echo $recordRS | sed 's/.*{"code":"\([0-9]*\)".*/\1/')
    recordIP=$(echo $recordRS | sed 's/.*,"value":"\([0-9a-z\.:]*\)".*/\1/')

    # Output IP
    if [ "$recordIP" = "$newDomainIP" ]; then
        if [ "$recordCD" = "1" ]; then
            echo $recordIP
            return 0
        fi
        # Echo error message
        echo $recordRS | sed 's/.*,"message":"\([^"]*\)".*/\1/'
        return 1
    else
        echo $recordIP #"Add Failed! Please check your network."
        return 1
    fi
}

# Update domain IP
# arg: main domain  sub domain
modifyDomainIP() {
    local domainID recordID recordRS recordCD recordIP

    # Get domain ID
    domainID=$(dnsapi "Domain.Info" "domain=${1}")
    domainID=$(echo $domainID | sed 's/.*{"id":"\([0-9]*\)".*/\1/')
    #echo $domainID
    # Get Record ID
    recordID=$(dnsapi "Record.List" "domain_id=${domainID}&record_type=${record_type}&sub_domain=${2}")
    recordID=$(echo $recordID | sed 's/.*\[{"id":"\([0-9]*\)".*/\1/')
    #echo $recordID
    # Update IP
    recordRS=$(dnsapi "Record.Modify" "domain_id=${domainID}&sub_domain=${2}&record_type=${record_type}&record_id=${recordID}&record_line=默认&value=${newDomainIP}")
    recordCD=$(echo $recordRS | sed 's/.*{"code":"\([0-9]*\)".*/\1/')
    recordIP=$(echo $recordRS | sed 's/.*,"value":"\([0-9a-z\.:]*\)".*/\1/')

    # Output IP
    if [ "$recordIP" = "$newDomainIP" ]; then
        if [ "$recordCD" = "1" ]; then
            echo $recordIP
            return 0
        fi
        # Echo error message
        echo $recordRS | sed 's/.*,"message":"\([^"]*\)".*/\1/'
        return 1
    else
        echo $recordIP #"Update Failed! Please check your network."
        return 1
    fi
}

# DDNS Check
# Arg: Main Sub
checkDomainIP() {
    local postRS
    local domainIP=$(getDomainIP $1 $2)
    newDomainIP=$(arIpAddress)

    if [ "$domainIP" != "" ]; then
        echo "domainIP:    ${domainIP}"
        echo "newDomainIP: ${newDomainIP}"
        if [ "$domainIP" != "$newDomainIP" ]; then
            postRS=$(modifyDomainIP $1 $2)
            if [ $? -eq 0 ]; then
                echo "update to ${postRS} successed."
                return 0
            else
                echo "postRS: ${postRS}"
                return 1
            fi
        fi
        echo "Last IP is the same as current, no action."
        return 1
    else
        newDomainIP=$(arIpAddress)
        postRS=$(addDomainIP $1 $2)
        if [ $? -eq 0 ]; then
            echo "add to ${postRS} successed."
            return 0
        else
            echo "postRS: ${postRS}"
            return 1
        fi
    fi
}

# ipv6批量动态域名解析
# Arg: Main Sub Sub Sub ……
 ddnspod() {
    local localIP=$(arIpAddress)
    echo "localIP: ${localIP}"

    # 支持多个子域名
    # 兼容dash，for array 无法使用
    i=2
    while test $i -le $#; do
        local cmd="echo \$$i"
        local subDomain=$(eval $cmd)
        echo ''
        echo "Updating Domain: ${subDomain}.${1}"
        checkDomainIP $1 ${subDomain}
        i=$(( $i + 1 ))
    done

    return 1
}

ddnspod $DOMAIN $SUB_DOMAIN
